package com.fanrui.code.family;

import java.util.Collection;
import java.util.concurrent.TimeUnit;

import org.apache.ibatis.session.SqlSession;

import com.fanrui.code.db.jvmdb.JvmDao;
import com.fanrui.code.entity.FamilyListMapper;
import com.fanrui.code.player.Player;
import com.fanrui.code.thread.MainLoopPlus.StrongRunnable;
import com.fanrui.code.util.core.LoopThreadPool;
import com.fanrui.code.util.logger.Stdout;
import com.fanrui.code.util.SessionUtil;

public class FamilyMemberDao extends JvmDao<FamilyMember, Player> {
	// singleton
	private FamilyMemberDao() {
		super(FamilyMember.class);
		LoopThreadPool.getInstance().scheduleAtFixedRate(new StrongRunnable() {

			@Override
			protected void strongRun() throws Exception {
				updateToDB();
			}

		}, 5, 5, TimeUnit.SECONDS);
	}

	private static class FamilyMemberDaoSingleton {
		private static FamilyMemberDao instance = new FamilyMemberDao();
	}

	public static FamilyMemberDao getInstance() {
		return FamilyMemberDaoSingleton.instance;
	}

	/**
	 * 定时更新需要修改的数据到数据库
	 */
	public void updateToDB() {
		if (modifiedEntities != null && !modifiedEntities.isEmpty()) {
			synchronized (modifiedEntities) {
				Stdout.GET().info("FamilyList:定时更新数据到数据库!此次更新{}条数据", modifiedEntities.size());
				try (SqlSession session = SessionUtil.getSession()) {
					FamilyListMapper um = session.getMapper(FamilyListMapper.class);
					for (FamilyMember familyMember : modifiedEntities.keySet()) {
						um.updateByKey(familyMember.toFamilyList());
					}
					modifiedEntities.clear();
					session.commit();
					session.close();
				}
			}
		}

	}

	@Override
	protected Collection<FamilyMember> dbFindAll() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected void OtherSave4jvm(FamilyMember entity) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void otherDelete4Jvm(FamilyMember entity) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void dbSave(FamilyMember t) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void dbDelete(Player entityId) {
		// TODO Auto-generated method stub

	}
}
